﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SES.CMS.BL;
using SES.CMS.DO;
using System.Data;
using System.Web.UI.HtmlControls;

namespace SES.CMS
{
    public partial class ProductCategory : System.Web.UI.Page
    {
        cmsProductBL data = new cmsProductBL();
        cmsProductDO itemProductDO = new cmsProductDO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
                LoadDrop();
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                int productCategoryID = int.Parse(Request.QueryString["ID"]);
                if (!IsPostBack)
                {
                    if (Session["shop"] == null)
                    {
                        Session["shop"] = new MyShopCart();
                    }
                    LoadProduct(productCategoryID);
                }
                cmsProductCategoryDO objCategory = new cmsProductCategoryBL().Select(new cmsProductCategoryDO() { ProductCategoryID = productCategoryID });
                lblCateName.Text = objCategory.ProductCategoryTitle;
                HtmlMeta metaKey = new HtmlMeta();
                metaKey.Name = "keywords";
                metaKey.Content = objCategory.Description;
                Page.Header.Controls.Add(metaKey);
                HtmlMeta metaDesc = new HtmlMeta();
                metaDesc.Name = "description";
                metaDesc.Content = objCategory.Description;
                Page.Header.Controls.Add(metaDesc);

                Page.Title = objCategory.ProductCategoryTitle + " | " + Ultility.WebTitle();
            }
            else if (!string.IsNullOrEmpty(Request.QueryString["PriceId"]))
            {
                int priceId = Convert.ToInt32(Request.QueryString["PriceId"]);

                SearchPriceDO itemSearchPrice = new SearchPriceDO();
                itemSearchPrice.Id = priceId;
                itemSearchPrice = new SearchPriceBL().Select(itemSearchPrice);
                object fromPrice = string.Format("{0:0,0}", itemSearchPrice.FromPrice).ToString().Replace(",", "");
                object toPrice = string.Format("{0:0,0}", itemSearchPrice.ToPrice).ToString().Replace(",","");

                if (!IsPostBack)
                {
                    LoadProductByPrice(fromPrice, toPrice);
                }

                lblCateName.Text = "Kết quả tìm kiếm";
                HtmlMeta metaKey = new HtmlMeta();
                metaKey.Name = "keywords";
                metaKey.Content = "Kết quả tìm kiếm TopBike";
                Page.Header.Controls.Add(metaKey);
                HtmlMeta metaDesc = new HtmlMeta();
                metaDesc.Name = "description";
                metaDesc.Content = "Kết quả tìm kiếm TopBike";
                Page.Header.Controls.Add(metaDesc);

                Page.Title = " Kết quả tìm kiếm | " + Ultility.WebTitle();
            }
            else if (!string.IsNullOrEmpty(Request.QueryString["OriginId"]))
            {
                int OriginId = Convert.ToInt32(Request.QueryString["OriginId"]);
                cmsOriginDO itemDO = new cmsOriginDO();
                itemDO.OriginID = OriginId;
                itemDO = new cmsOriginBL().Select(itemDO);
                string name = itemDO.Origin;
                if (!IsPostBack)
                {
                    LoadProductByOriginId(OriginId);
                }
                lblCateName.Text = name ;
                Page.Title = name + " | " + Ultility.WebTitle();
            }
            else
            {
                lblCateName.Text = "Danh sách sản phẩm";
                //   rptNewProductDataSource(0);
                Page.Title = " Danh sách sản phẩm | " + Ultility.WebTitle();
                if (!IsPostBack) LoadProduct(0);
            }
        }

        void LoadDrop()
        {
            dropOrigin.Items.Clear();
            dropCateProduct.Items.Clear();
            cmsOriginBL itemOriginBL = new cmsOriginBL();
            cmsProductCategoryBL itemProCate = new cmsProductCategoryBL();
            DataTable tbProCate = itemProCate.SelectAll();
            DataTable tbOrigin = itemOriginBL.SelectAll();

            ListItem itemRoot = new ListItem("---- Chọn hãng xe ----", "0");
            dropOrigin.Items.Insert(0, itemRoot);
            foreach (DataRow item in tbOrigin.Rows)
            {
                string name = item["Origin"].ToString();
                string id = item["OriginID"].ToString();
                ListItem ltItem = new ListItem(" -- " + name, id);
                dropOrigin.Items.Add(ltItem);
            }

            ListItem itemRoot1 = new ListItem("---- Chọn loại xe ----", "0");
            dropCateProduct.Items.Insert(0, itemRoot1);
            foreach (DataRow item in tbProCate.Rows)
            {
                string name = item["ProductCategoryTitle"].ToString();
                string id = item["ProductCategoryID"].ToString();
                ListItem ltItem = new ListItem(" -- " + name, id);
                dropCateProduct.Items.Add(ltItem);
            }
        }

        void Search()
        {
            int procateId = -1;
            int originId = -1;
            object fromPrice = 0;
            object toPrice = 0;
            int isPrice = 1;
            if (dropCateProduct.SelectedValue != "0")
            {
                procateId = int.Parse(dropCateProduct.SelectedValue);
            }
            if (dropOrigin.SelectedValue != "0")
            {
                originId = int.Parse(dropOrigin.SelectedValue);
            }
            if (txtFromPrice.Text != "")
            {
                fromPrice = int.Parse(txtFromPrice.Text);
            }
            if (txtToPrice.Text != "")
            {
                toPrice = int.Parse(txtToPrice.Text);
            }
            if (txtToPrice.Text != "" && txtFromPrice.Text != "")
            {
                isPrice = 0;
            }

            search(procateId, originId, fromPrice, toPrice, isPrice);
            //if (hdfx.Value.Equals("0"))
            //{
            //    grvFinger.DataSource = new FingerPrintBL().SelectAdmin(-1, -1, DateTime.Now, DateTime.Now, 1, 0, businessCenterID);
            //}
            //else if (hdfx.Value.Equals("1"))
            //{
            //    grvFinger.DataSource = new FingerPrintBL().SelectAdmin(int.Parse(ddlStatus.SelectedValue), -1, DateTime.Now, DateTime.Now, 1, 0, businessCenterID);
            //}
            //else if (hdfx.Value.Equals("2"))
            //{
            //    if (!txtFromDate.Text.Trim().Equals("") && !txtToDate.Text.Trim().Equals(""))
            //        grvFinger.DataSource = new FingerPrintBL().SelectAdmin(-1, -1, Ultility.ReturnValidateDateTime(txtFromDate.Text.Trim()), Ultility.ReturnValidateDateTime(txtToDate.Text.Trim()), 0, -1, businessCenterID);
            //}
        }

        public int CurrentPage
        {
            get
            {
                // look for current page in ViewState
                object o = this.ViewState["_CurrentPage"];
                if (o == null)
                    return 0;	// default to showing the first page
                else
                    return (int)o;
            }

            set
            {
                this.ViewState["_CurrentPage"] = value;
            }
        }

        private void bindatalist(DataTable dt)
        {
            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = dt.DefaultView;
            objPds.AllowPaging = true;
            objPds.PageSize = 28;
            objPds.CurrentPageIndex = CurrentPage;
            cmdPrev.Visible = !objPds.IsFirstPage;
            cmdNext.Visible = !objPds.IsLastPage;
            rptNewProduct.DataSource = objPds;
            rptNewProduct.DataBind();
        }
        protected void cmdPrev_Click(object sender, ImageClickEventArgs e)
        {
            CurrentPage -= 1;

            // Reload control
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                LoadProduct(int.Parse(Request.QueryString["ID"].ToString()));
            }
            else
            {
                LoadProduct(0);
            }
        }
        private void LoadProduct(int productCategoryID)
        {
            bindatalist(new cmsProductBL().SelectByProductCategoryAll(productCategoryID));
        }

        private void LoadProductByPrice(object fromPrice, object toPrice)
        {
            bindatalist(new cmsProductBL().GetByPrice(fromPrice, toPrice));
        }

        private void LoadProductByOriginId(int OriginId)
        {
            bindatalist(new cmsProductBL().GetByOriginID(OriginId));
        }

        void search(int proCateId, int OriginId, object fromPrice, object toPrice, int IsPrice)
        { 
            bindatalist(new cmsProductBL().SearchSenior(proCateId,OriginId,fromPrice,toPrice,IsPrice));
        }
        protected void cmdNext_Click(object sender, ImageClickEventArgs e)
        {
            CurrentPage += 1;
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                LoadProduct(int.Parse(Request.QueryString["ID"].ToString()));
            }
            else
            {
                LoadProduct(0);
            }
        }
        //private void rptNewProductDataSource(int productCategoryID)
        //{

        //    CollectionPager1.MaxPages = 10000;

        //    CollectionPager1.PageSize = 4; // số items hiển thị trên một trang

        //    CollectionPager1.DataSource = new cmsProductBL().SelectByProductCategoryAll(productCategoryID).DefaultView;

        //    CollectionPager1.BindToControl = rptNewProduct;
        //    rptNewProduct.DataSource = CollectionPager1.DataSourcePaged;
        //    rptNewProduct.DataBind();
        //}
        protected string FriendlyUrl(string s)
        {
            return Ultility.Change_AV(s);
        }
        protected void rptNewProduct_ItemDataBound(object source, RepeaterCommandEventArgs e)
        {
            int productID = int.Parse(e.CommandArgument.ToString());
            if (e.CommandName.Equals("AddToCart"))
            {
                AddItem(productID);
            }
        }
        private void AddItem(int productID)
        {
            cmsProductDO itemDO = new cmsProductDO();
            itemDO.ProductID = productID;
            //itemDO.ProductID = idProduct;
            cmsProductDO product = data.Select(itemDO);
            if (product != null)
            {
                ProductShop item = new ProductShop();
                item.Id = product.ProductID;
                item.Image = product.ProductImage;
                item.Name = product.ProductTitle;
                if (product.IsPromotion) //  Kiểm tra sản phẩm có khuyến mãi thì tính giá khuyến mãi(saleprice). ko thì tính giá bình thường(price)
                {
                    if (product.SalePrice == null || product.SalePrice.ToString().Equals(""))
                    {
                        item.Cost = 0;
                    }
                    else
                    {
                        item.Cost = (decimal)product.SalePrice;
                    }
                }
                // Sản phẩm không có giá khuyến mãi
                else
                {
                    if (product.Price == null || product.Price.ToString().Equals(""))
                        item.Cost = 0;
                    else
                    {

                        item.Cost = (decimal)product.Price;
                    }
                }
                item.Quantity = 1;
                ((MyShopCart)Session["shop"]).Add(item);
            }
            //Response.Redirect(this.Request.Url.ToString());
            Ultility.Alert("Đặt hàng thành công", Request.Url.AbsolutePath);
            // ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>$(document).ready(fuction(){ $('[id*=btnPopup]').live('click', function () { $('#dialog').dialog({title: 'jQuery Dialog Popup',buttons: { Close: function () {$(this).dialog('close'); }} }); return false;}); });</script>", false);
        }

        protected void btnSearchs_Click(object sender, EventArgs e)
        {
            Search();
        }
    }
}